/**
 * 
 */
package org.statewalker.parser.wiki.tokenizer.block;

import org.statewalker.parser.wiki.grammar.WikiBlockDict;
import org.statewalker.tokenizer.CharStream;
import org.statewalker.tokenizer.ITokenizer;
import org.statewalker.tokenizer.StreamToken;
import org.statewalker.tokenizer.CharStream.Marker;
import org.statewalker.tokenizer.CharStream.Pointer;
import org.statewalker.tokenizer.base.NewLineTokenizer;

public class TableCellTokenizer implements ITokenizer {

    private String fCellKey;

    private String fRowKey;

    public TableCellTokenizer() {
        this(WikiBlockDict.TR, WikiBlockDict.TD);
    }

    public TableCellTokenizer(String rowKey, String cellKey) {
        super();
        fCellKey = cellKey;
        fRowKey = rowKey;
    }

    public StreamToken read(CharStream stream) {
        StreamToken result = null;
        Marker marker = stream.markPosition();
        try {
            Pointer position = stream.getPointer();
            boolean row = NewLineTokenizer.readNewLine(stream) != null
                || position.column == 0;
            String key = row ? fRowKey : fCellKey;
            if (key == null)
                return null;
            char ch = stream.getChar();
            if (ch != '|')
                return null;
            stream.incPos();
            result = new StreamToken(key, position, stream.getPointer(), "|");
            return result;
        } finally {
            marker.close(result == null);
        }
    }
}